import json
import time

from django.utils.deprecation import MiddlewareMixin

from common.base import logger


class LogMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 存放请求过来时的时间
        request.init_time = time.time()
        remote_address = request.META.get('X-Real-IP') if request.META.get('X-Real-IP') else request.META.get(
            "REMOTE_ADDR")
        try:
            params = json.loads(request.body)
        except:
            params = {}
        headers_info = "\n\t".join([f"{k}={v}" for k, v in request.headers.items()])
        msg = ("\n" + " Request Start ".center(100, '*')
               + f"\nrequest ip：{remote_address}"
               + f"接口: {request.method} {request.path}\n"
               + f"请求头：{headers_info}\n"
               + f"请求参数（get）：{json.dumps(request.GET)}\n"
               + f"请求体参数：{params}\n"
               + " Request End ".center(100, '*') + "\n"
               )
        logger.info(msg)
        return None

    def process_response(self, request, response):
        msg = ("\n" + " Response Start ".center(100, '*')
               + f"\nResult: {response.data}\n耗时: {time.time() - request.init_time}\n"
               + " Response End ".center(100, '*') + "\n"
               )
        logger.info(msg)
        return response
